<?php

class PayTtCheckOrderService
{
    /**
     * @var PayTtCheckOrderService
     */
    private static $instance;

    /**
     * Get the instance of PayTtCheckOrderService
     * @return PayTtCheckOrderService
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new PayTtCheckOrderService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    public function __construct()
    {

    }

    /**
     * 扣除余额
     * @param $userId
     * @param $amt
     * @param $bill_no
     * @param $platform
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function ttDeductComplete($userId,$amt,$bill_no,$platform,$reqTime)
    {
        $results = array(
            'status' => -1,
            'items' => '',
            'itemStr' => '',
        );

        //查询数据库，订单是否存在
        /**
         * @var ModulePaymentOrderVoList $paymentList
         * @var ModulePaymentOrderVo $payment
         */
        $paymentList = SzPersister::get()->getVoList($userId, ModulePaymentConst::ORM_NAME_PAYMENT_ORDER);
        $paymentDatas = $paymentList->toArray();
        if(empty($paymentDatas)){
            $results = array(
                'status' => -1,
                'items' => '',
                'itemStr' => '',
            );
            return $results;
        }

        $orderInfo=false;
        foreach ($paymentDatas as $id=>$data) {
            $saveOrderNo = $data['paymentDefId'];
            if ($saveOrderNo == $bill_no){
                $orderId = $data['orderId'];
                $payment= $paymentList->getElement($orderId,false);
                $orderInfo=true;
                break;
            }
        }

        //是否有订单
        if (!$orderInfo) {
            $results = array(
                'status' => -1,
                'items' => '',
                'itemStr' => '',
            );
            return $results;
        }

        if ($payment->getStatus()  == 1) {
            //订单已支付
            $results = array(
                'status' => 2,
                'items' => '',
                'itemStr' => '',
            );

        }elseif ($payment->getStatus()  == 0) {
            //扣除游戏币
            $amt = $payment->getPrice();
            //充值测试白名单
            if (in_array($userId,GameConst::GAME_TT_TEST_USERID)){
                $amt = 1;
            }
            $deductRes = PayTtService::get()->ttDeduct($userId,$amt,$bill_no,$platform,$reqTime);
            error_log('ttdeduct_errcode==>'.$deductRes['errcode']."\r\n",3,$_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
            if ($deductRes['errcode'] == 0){
                error_log('ttdeduct_balance==>'.$deductRes['balance']."\r\n",3,$_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
                error_log('ttdeduct_bill_no==>'.$deductRes['bill_no']."\r\n",3,$_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
                //修改订单状态，并发放道具
                $orderId = $payment->getOrderId();
                error_log('ttdeduct_orderId==>'.$orderId."\r\n",3,$_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
                PayTtCompletedService::get()->ttPayCompleted($userId,$orderId);

                //订单成功 1
                //进行道具发放，返回给前端展示用
                $extraArr =  json_decode($payment->getExtra(),true);
                $type = $extraArr['type'];
                $count = $extraArr['count'];
                $indexId = $extraArr['goodId'];
                $isFirstPay = $extraArr['isFirstPay'];//钻石是否首充

                $giftConf = array();
                //充值购买物品配置表获取==>1:ft_diamond_gift_pack---2:ft_game_pay---3:ft_diamond_value
                if ($type == 1){//等级段礼包礼包和玫瑰礼包
                    $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_GIFT_PACK, $indexId, true);
                }
                if ($type == 2){//钻石，钻石页签的内容
                    $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_PAY, $indexId, true);
                }
                if ($type == 3){//钻石价值表，金币页签和特惠页签的内容
                    $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $indexId, true);
                }
                if (empty($giftConf)){
                    return $results;
                }

                $result = $this->branchShop($userId,$giftConf,$type,$indexId,$count,$reqTime,$isFirstPay);

                $results = array(
                    'status' => 1,
                    'items' => $result['items'],
                    'itemStr' => $result['itemStr'],
                );
            }
        }

        return $results;
    }

    /**
     * 查询订单结果
     * @param $userId
     * @param $orderNo
     * @param $reqTime
     * @return array|bool|void
     * @throws SzException
     */
    public function ttCheckOrder($userId,$orderNo,$reqTime)
    {
        error_log('*****查询开始'."\r\n",3,$_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
        $results = array(
            'status' => -1,
            'items' => '',
            'itemStr' => '',
        );
        //查询数据库，订单是否存在
        /**
         * @var ModulePaymentOrderVoList $paymentList
         * @var ModulePaymentOrderVo $payment
         */
        $paymentList = SzPersister::get()->getVoList($userId, ModulePaymentConst::ORM_NAME_PAYMENT_ORDER);
        $paymentDatas = $paymentList->toArray();
        if(empty($paymentDatas)){
            $results = array(
                'status' => -1,
                'items' => '',
                'itemStr' => '',
            );
            return $results;
        }

        $orderInfo=false;
        foreach ($paymentDatas as $id=>$data) {
            $saveOrderNo = $data['paymentDefId'];
            if ($saveOrderNo == $orderNo){
                $orderId = $data['orderId'];
                $payment= $paymentList->getElement($orderId,false);
                $orderInfo=true;
                break;
            }
        }




        //是否有订单
        if (!$orderInfo) {
            $results = array(
                'status' => -1,
                'items' => '',
                'itemStr' => '',
            );
            return $results;
        }

        if ($payment->getStatus()  == 0 ) {
            //正在处理 0
                $results = array(
                    'status' => 0,
                    'items' => '',
                    'itemStr' => '',
                );
        }elseif ($payment->getStatus()  == 2) {
            //订单失败 2
                    $results = array(
                        'status' => 2,
                        'items' => '',
                        'itemStr' => '',
                    );
        }elseif ($payment->getStatus()  == 1) {
            //订单成功 1
            //进行道具发放，返回给前端展示用
            $extraArr =  json_decode($payment->getExtra(),true);
            $type = $extraArr['type'];
            $count = $extraArr['count'];
            $indexId = $extraArr['goodId'];
            $isFirstPay = $extraArr['isFirstPay'];//钻石是否首充

           $giftConf = array();
            //充值购买物品配置表获取==>1:ft_diamond_gift_pack---2:ft_game_pay---3:ft_diamond_value
            if ($type == 1){//等级段礼包礼包和玫瑰礼包
                $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_GIFT_PACK, $indexId, true);
            }
            if ($type == 2){//钻石，钻石页签的内容
                $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_PAY, $indexId, true);
            }
            if ($type == 3){//钻石价值表，金币页签和特惠页签的内容
                $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $indexId, true);
            }
            if (empty($giftConf)){
                return $results;
            }

            $result = $this->branchShop($userId,$giftConf,$type,$indexId,$count,$reqTime,$isFirstPay);

            $results = array(
                'status' => 1,
                'items' => $result['items'],
                'itemStr' => $result['itemStr'],
            );
        }

        return $results;

    }

    /**
     * 购买逻辑分支(不发货，只验证)
     * @param $userId
     * @param $giftConf
     * @param $type
     * @param $indexId
     * @param $count
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function branchShop($userId,$giftConf,$type,$indexId,$count,$reqTime,$isFirstPay){
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        $changeRes = array();
        //充值购买物品配置表获取==>1:ft_diamond_gift_pack---2:ft_game_pay---3:ft_diamond_value
        if ($type == 1){//等级段礼包礼包和玫瑰礼包
            $changeRes = $this->buyDiamondGiftPack($userId,$giftConf,$count,$reqTime);
        }
        if ($type == 2){//钻石，钻石页签的内容
            $batch = 9;
            $changeRes = $this->buyGamePayNew($userId,$giftConf,$reqTime,$batch,$isFirstPay);
        }
        if ($type == 3){//钻石价值表，金币页签和特惠页签的内容
            $changeRes = $this->buyDiamondValue($userId,$indexId);
        }

        if ($changeRes['code'] == 0){
            $res['code'] = $changeRes['code'];
            $res['items'] = $changeRes['items'];
            $res['itemStr'] = $changeRes['itemStr'];
        }

        return $res;
    }

    /**
     * 等级段礼包礼包和玫瑰礼包
     * @param $userId
     * @param $giftConf
     * @param $count
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function buyDiamondGiftPack($userId,$giftConf,$count,$reqTime){
        $getReward = array();
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        $diamond = 0;
        /**
         * @var ModuleItemVoList $itemList
         */
        $itemList = null;
        $index = 0;
        foreach ($giftConf['rewardProps'] as $entityId => $count) {
            $index++;
            /*    if ($giftConf['type'] == 3) {//组合礼包
                    $itemList = is_null($itemList) ? SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM) : $itemList;
                    list($action, $module, $itemDefId) = EntityService::get()->parseEntityId($entityId);
                    if ($action == GameConst::ENTITY_ACTION_GET && $module == GameConst::ENTITY_TYPE_ITEM) {
                        $itemSetting = SzConfig::get()->loadAppConfig(ModuleItemConst::CONFIG_ITEM_DEFS, $itemDefId, true);
                        if ($itemSetting['category'] == GameConst::ITEM_CATEGORY_CULTIVATE_CARD) {
                            $item = $itemList->getElementsByItemDefId($itemDefId);
                            if ($item) {//组合礼包中如果有培育卡且已经获得过则换成对应的钻石
                                $diamond += $giftConf['conversionRatio'][$index - 1];
                                continue;
                            }
                        }
                    }
                }*/

            //记录所获得物品
            if (!isset($getReward[$entityId])){
                $getReward[$entityId] = $count;
            }
            else{
                $getReward[$entityId] = $getReward[$entityId] + $count;
            }
        }

        foreach ($giftConf['diamond'] as $entityId => $count) {
            if ($entityId == GameConst::ENTITY_ACTION_GET_MONEY && $count > 0) {
                $diamond += $count;
            }
        }

        if ($diamond > 0) {
            //记录所获得物品
            if (!isset($getReward[GameConst::ENTITY_ACTION_GET_MONEY])){
                $getReward[GameConst::ENTITY_ACTION_GET_MONEY] = $count;
            }
            else{
                $getReward[GameConst::ENTITY_ACTION_GET_MONEY] = $getReward[GameConst::ENTITY_ACTION_GET_MONEY] + $count;
            }
        }

        if (!empty($getReward)){
            $res['code'] = 0;
            $res['items'] = $getReward;
        }

        return $res;
    }

    /**
     * 钻石，钻石页签的内容
     * @param $userId
     * @param $giftConf
     * @param $reqTime
     * @param $activityId
     * @return array
     * @throws SzException
     */
    public function buyGamePay($userId,$giftConf,$reqTime,$activityId){
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        $totalMoney = 0;
        $money = $giftConf['price']*10;
        $activity = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, $activityId, true);

        $gamePaySettings = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_PAY, null, true);
        $reward = array();
        foreach ($gamePaySettings as $gamePaySetting) {
            if ($gamePaySetting['count'] == $money) {
                $reward = $gamePaySetting;
                break;
            }
        }

        if (!$reward) {
            return $res;
        }

        /**
         * @var $activityFirstPayList ActivityFirstPayVoList
         * @var $activityFirstPay ActivityFirstPayVo
         */
        $activityFirstPayList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_FIRST_PAY);
        $activityFirstPay = $activityFirstPayList->getElement($money,false);
        if ($activityFirstPay) {
            $totalMoney = $money;

        } else {
            $totalMoney = $money*2;

        }
        $res['code'] = 0;
        $res['items'][GameConst::ENTITY_ACTION_GET_MONEY] = $totalMoney;

        return $res;
    }

    /**
     * 钻石，钻石页签的内容 (趣头条使用，查询订单ext  判断是不是首充)
     * @param $userId
     * @param $giftConf
     * @param $reqTime
     * @param $activityId
     * @return array
     * @throws SzException
     */
    public function buyGamePayNew($userId,$giftConf,$reqTime,$activityId,$isFirstPay){
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        $totalMoney = 0;
        $money = $giftConf['price']*10;
        $activity = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, $activityId, true);

        $gamePaySettings = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_PAY, null, true);
        $reward = array();
        foreach ($gamePaySettings as $gamePaySetting) {
            if ($gamePaySetting['count'] == $money) {
                $reward = $gamePaySetting;
                break;
            }
        }

        if (!$reward) {
            return $res;
        }

        /**
         * @var $activityFirstPayList ActivityFirstPayVoList
         * @var $activityFirstPay ActivityFirstPayVo
         */

        if ($isFirstPay) {
            $totalMoney = $money*2;

        } else {
            $totalMoney = $money;

        }
        $res['code'] = 0;
        $res['items'][GameConst::ENTITY_ACTION_GET_MONEY] = $totalMoney;

        return $res;
    }

    /**
     * 钻石价值表，金币页签和特惠页签的内容
     * @param $userId
     * @param $indexId
     * @return array
     * @throws SzException
     */
    public function buyDiamondValue($userId,$indexId){
        $getReward = array();
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        $diamondSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $indexId, true);

        foreach ($diamondSetting['item'] as $entityId => $count) {
            //记录所获得物品
            if (!isset($getReward[$entityId])){
                $getReward[$entityId] = $count;
            }
            else{
                $getReward[$entityId] = $getReward[$entityId] + $count;
            }
        }
        if (!empty($diamondSetting)){
            $res['itemStr'] = $diamondSetting['specialId'];
        }

        $res['code'] = 0;
        $res['items'] = $getReward;
        return $res;
    }
}
